package com.quick.springbootquicky.controller;

import com.quick.springbootquicky.pojo.Category;
import com.quick.springbootquicky.service.CategoryService;
import com.quick.springbootquicky.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    /**
     * 文章新增
     * @param category @Validated 验证参数不能为空，还要在属性字段上添加对应注解才有效
     * @return
     *     @Validated(Category.Add.class)注解说明
     *     @NotNull(groups = Update.class)//说明只有在更新时候才会校验id参数是否有值
     *     private Integer id;// 'ID',
     */
    @PostMapping("/insert")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        categoryService.add(category);
        return Result.success("新增成功");
    }

    /**
     *  查询文章列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> list(){
        List<Category> list = categoryService.list();
        return Result.success("查询成功",list);
    }

    /**
     *  查询详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public Result<Category> detail(Integer id){
        if(null == id){
            return Result.error("参数有误");
        }
        Category c = categoryService.findById(id);
        return Result.success("查询成功",c);
    }

    /**
     * 根据id更新文章
     * @param category @Validated 注解判断参数是否为空，同时需要在实体类属性字段中添加具体注解才有效
     * @return
     *
     *     @Validated(Category.Update.class)注解说明
     *     @NotNull(groups = Update.class)//说明只有在更新时候才会校验id参数是否有值
     *     private Integer id;// 'ID',
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.update(category);
        return Result.success("更新成功");
    }

    /**
     * 删除文章,先判断文章分类有没有被引用
     * @param id
     */
    @DeleteMapping("/delete")
    public Result<String> delete(Integer id){
        categoryService.delete(id);
        return Result.success("删除成功");
    }

}
